package com.kaikai.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kaikai.commonutils.R;
import com.kaikai.edu.entity.EduTeacher;
import com.kaikai.edu.mapper.EduCourseMapper;
import com.kaikai.edu.mapper.EduTeacherMapper;
import com.kaikai.edu.service.EduTeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 讲师 服务实现类
 * </p>
 *
 * @author yujiankai
 * @since 2021-05-02
 */
@Service
public class EduTeacherServiceImpl extends ServiceImpl<EduTeacherMapper, EduTeacher> implements EduTeacherService {

    @Autowired
    private EduCourseMapper eduCourseMapper;

//获得首页4个名师信息
    @Cacheable(value = "teacher",key = "'4'")
    @Override
    public List<EduTeacher> list4_teachers() {
        QueryWrapper<EduTeacher> teacherWrapper=new QueryWrapper<>();
        teacherWrapper.orderByDesc("id");
        teacherWrapper.last("limit 4");
        List<EduTeacher> teachers = this.list(teacherWrapper);
        return teachers;
    }

    @Override
    public Map<String, Object> getTeacherFrontList(Page<EduTeacher> pageTeacher) {
        //先分页
        QueryWrapper<EduTeacher> wrapper=new QueryWrapper<>();
        wrapper.orderByDesc("id");
        //将分页数据存储到pageTeacher内
        baseMapper.selectPage(pageTeacher, wrapper);
        List<EduTeacher> records = pageTeacher.getRecords();
        long current = pageTeacher.getCurrent();
        long pages = pageTeacher.getPages();
        long size = pageTeacher.getSize();
        long total = pageTeacher.getTotal();
        boolean hasNext = pageTeacher.hasNext();
        boolean hasPrevious = pageTeacher.hasPrevious();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        return map;


    }

    @Override
    public R removeTeacherById(String teacherId) {
        //查找是否关联课程
        try {
            int i = eduCourseMapper.ifExistCourseForTeacher(teacherId);
            if (i>0) {
                return R.error().message("当前存在关联课程,请先删除");
            }else{
                int i1 = baseMapper.deleteById(teacherId);
                if(i1==1){
                    return R.ok().message("删除成功");
                }
                return R.error().message("删除失败");
            }
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
